package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 从数据库查出的正确的账号密码消息
 *
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper mapper;

    //AdminDetails 继承 User 类
    @Override
    public AdminDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("spring security 即将调用【loadUserByUsername】的方法，参数：{}",username);

        AdminLoginInfoVO adminLoginInfoVO = mapper.getLoginInfoByUsername(username);
        log.debug("loginInfoVO的参数：{}", adminLoginInfoVO);

        if(adminLoginInfoVO == null){
            log.debug("该用户名【{}】不存在，即将抛出异常",username);
            String message = "登录失败，用户名不存在";
            throw new BadCredentialsException(message);
        }

        //准备权限信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = adminLoginInfoVO.getPermissions();
        for (String permission : permissions) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        //准备id信息
        Long id = adminLoginInfoVO.getId();
        //准备用户名信息
        username = adminLoginInfoVO.getUsername();
        //准备密码信息
        String password = adminLoginInfoVO.getPassword();
        //准备是否启用信息
        Integer enable = adminLoginInfoVO.getEnable();

        AdminDetails adminDetails = new AdminDetails(username,password,enable == 1,authorities);
        adminDetails.setId(id);
        /*UserDetails userDetails = User.builder()
                .username(loginInfoVO.getUsername())
                .password(loginInfoVO.getPassword())
                .accountExpired(false)//账号是否过期
                .accountLocked(false)//是否锁定
                .disabled(loginInfoVO.getEnable() == 0)//是否禁用
                .authorities("一个仅占用的权限文本")// 权限，注意，此方法的参数不可以为null，在不处理权限之前，可以写一个随意的字符串值
                .build();
        log.debug("即将向spring security返回userDetails对象，参数{}",userDetails);
        */
        return adminDetails;
    }
}
